package com.kaowen.spider.util;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.apache.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

public class BaseAdapter {

	private static Logger logger = Logger.getLogger(BaseAdapter.class);

	protected Map<String, String> cookies = new HashMap<String, String>();

	public BaseAdapter() {
		// 设置SSL协议，信任所有证书
		trustEveryone();
		logger.debug("设置ssl协议，信任所有证书");
	}

	/**
	 * 设置信任所有证书，用户访问SSL链接
	 */
	private void trustEveryone() {
		try {
			HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
				public boolean verify(String hostname, SSLSession session) {
					return true;
				}
			});

			SSLContext context = SSLContext.getInstance("TLS");
			context.init(null, new X509TrustManager[] { new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return new X509Certificate[0];
				}
			} }, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
		} catch (Exception e) {
			// e.printStackTrace();
		}
	}

	/**
	 * 执行URL访问
	 * 
	 * @param url
	 * @param method
	 * @param params
	 * @param headers
	 * @return
	 */
	public Response execute(String url, Method method, Map<String, String> params, Map<String, String> headers) {
		logger.debug("执行" + method.toString() + "请求." + "\nurl:" + url + "\nparams"
				+ (params == null ? "" : params.toString()) + "\nheaders" + (headers == null ? "" : headers.toString()));
		Connection conn = Jsoup.connect(url);
		conn.timeout(30000);
		conn.ignoreContentType(true);
		conn.ignoreHttpErrors(true);
		conn.cookies(cookies);
		conn.method(method);
		if (params != null && params.size() > 0) {
			Iterator<String> iter = params.keySet().iterator();
			while (iter.hasNext()) {
				String key = iter.next();
				String value = params.get(key);
				if (value != null)
					conn.data(key, value);
			}
		}
		if (headers != null && headers.size() > 0) {
			Iterator<String> iter = headers.keySet().iterator();
			while (iter.hasNext()) {
				String key = iter.next();
				conn.header(key, headers.get(key));
			}
		}
		Response resp = null;
		try {
			resp = conn.execute();
			if (resp != null) {
				logger.debug("返回代码：" + resp.statusCode());
				Map<String, String> respCookie = resp.cookies();
				if (respCookie != null) {
					cookies.putAll(respCookie);
					logger.debug("设置Cookie:" + respCookie.toString());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			resp = conn.response();
		}
		return resp;
	}

	/**
	 * 执行HTTP GET操作
	 * 
	 * @param url
	 * @return
	 */
	public Response get(String url) {
		return execute(url, Method.GET, null, null);
	}

	/**
	 * 执行HTTP GET操作
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public Response get(String url, Map<String, String> params) {
		return execute(url, Method.GET, params, null);
	}

	/**
	 * 执行HTTP GET操作
	 * 
	 * @param url
	 * @param params
	 * @param headers
	 * @return
	 */
	public Response get(String url, Map<String, String> params, Map<String, String> headers) {
		return execute(url, Method.GET, params, headers);
	}

	/**
	 * 执行HTTP POST操作
	 * 
	 * @param url
	 * @return
	 */
	public Response post(String url) {
		return execute(url, Method.POST, null, null);
	}

	/**
	 * 执行HTTP POST操作
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public Response post(String url, Map<String, String> params) {
		return execute(url, Method.POST, params, null);
	}

	/**
	 * 执行HTTP POST操作
	 * 
	 * @param url
	 * @param params
	 * @param headers
	 * @return
	 */
	public Response post(String url, Map<String, String> params, Map<String, String> headers) {
		return execute(url, Method.POST, params, headers);
	}

	/**
	 * 获取当前Cookie
	 * 
	 * @return
	 */
	public Map<String, String> getCookies() {
		return cookies;
	}
}
